﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using AMM.Business;
using AMM.Business.Business;
using AMM.CustomWinControls;
using AMM.Model;
using AMM.Model.Business;
using AMM.Model.PrintModels;
using AMM.UserControls;
using Microsoft.Reporting.WinForms;

namespace AMM.Forms.Business {
    public partial class FrmProduceConduct : FrmProduceConductBase {

        private int _pageIndex;
        private ProduceConductSearchModel _searchModel;
        private ProduceConductProcessor _produceConductProcessor;
        private List<ProduceConductViewModel> _produceConductList;

        #region Override

        protected override string FunctionCode {
            get { return "AMM1204"; }
        }

        protected override BaseSearchControl SearchControl {
            get { return new ProduceConductSearchControl(); }
        }

        protected override void Add() {
            this.ResetForms();
            this.ShowEditForm("新增", new List<ProduceConduct>());
            base.Add();
        }

        protected override void Amend() {
            List<ProduceConductViewModel> selectedList = this.dgvProduceConductList.GetSelectedRows<ProduceConductViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            List<ProduceConduct> produceConductList = this._produceConductProcessor.FetchProduceConductListById(selectedList[0].Key);
            if (produceConductList.Any(x => x.ProcurementOrderId.HasValue)) {
                this.ShowError("指令单已经产生对应的采购单，不能修改！");
                return;
            }
            this.ShowEditForm("修改", produceConductList);
            base.Amend();
        }

        protected override void Save() {
            base.Save();
        }

        protected override void Delete() {
            List<ProduceConductViewModel> selectedList = this.dgvProduceConductList.GetSelectedRows<ProduceConductViewModel>();
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                this._produceConductProcessor.Delete(selectedList.Select(x => x.Key).ToArray());
                this.MDIParent.SetStatusInformation("删除成功");
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                base.Delete();
            });
        }

        protected override void Search(object sender, FrmSearch.SearchArgs e) {
            this.CreateNewThread(() => {
                if (e.IsRevert) {
                    this._searchModel = new ProduceConductSearchModel();
                }
                else {
                    this._searchModel = (ProduceConductSearchModel)e.SearchModel;
                }
            }, () => {
                this.BindProduceConductList();
            });
        }

        protected override void Print() {
            List<ProduceConductViewModel> selectedList = this.dgvProduceConductList.GetSelectedRows<ProduceConductViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                PrintDataSoruceHelper printDataSoruceHelper = new PrintDataSoruceHelper();
                List<PrintProduceConduct> printProduceConduct = printDataSoruceHelper.FetchPrintProduceConduct(selectedList[0].Key);
                List<PrintProduceConductDetails> printProduceConductDetails = printDataSoruceHelper.FetchPrintProduceConductDetails(selectedList[0].Key);

                this.PrintHelperIns = new PrintHelper("ProduceConductPrint.rdlc", this.Text);
                this.PrintHelperIns.ReportDataSources.Add(new ReportDataSource("ds", printProduceConduct));
                this.PrintHelperIns.ReportDataSources.Add(new ReportDataSource("ds1", printProduceConductDetails));
                base.Print();
            }, () => {
                // for hiding
                this.PrintHelperIns.Dispose();
            });
        }

        protected override void Complete() {
            List<ProduceConductViewModel> selectedList = this.dgvProduceConductList.GetSelectedRows<ProduceConductViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                ProduceConduct produceConduct = this._produceConductProcessor.FetchProduceConductById(selectedList[0].Key);
                if (!produceConduct.IsLocked) {
                    if (this.ShowQuestion("生产指令单完成的操作不可逆，请确认！") == DialogResult.No) { return; }
                    produceConduct.IsLocked = true;
                    produceConduct.ModifiedBy = LoginUserName;
                    produceConduct.ModifiedDatetime = DateTime.Now;
                    this._produceConductProcessor.Update(produceConduct);
                    this.MDIParent.SetStatusInformation("设置完成操作成功");
                }
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                base.Complete();
            });
        }

        #endregion

        public FrmProduceConduct() {
            this.InitializeComponent();

            this.dgvProduceConductList.DataGridViewModelType = typeof(ProduceConductViewModel);
        }

        #region Private methods

        private bool frmEdit_Edit(object sender, FrmEdit.EditArgs e) {
            bool resultFlag = false;
            List<ProduceConduct> produceConductList = (List<ProduceConduct>)e.EditModel;
            if (produceConductList.Count == 0) {
                this.ShowError("请添加生产指令单明细记录！");
                return false;
            }
            this.PreventCancel = true;
            this.CreateNewThread(() => {
                produceConductList.ForEach(x => {
                    if (x.ClassStatus == ClassStatus.Added) {
                        x.CreatedBy = LoginUserName;
                    }
                    else {
                        x.ModifiedBy = LoginUserName;
                    }
                });
                this._produceConductProcessor.Update(produceConductList);

                resultFlag = true;
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                if (resultFlag) {
                    this.MDIParent.SetStatusInformation("保存成功");
                    this.FormEdit.Close();
                }
            });

            this.Save();
            return true;
        }

        private void ResetForms() {
            this.BindProduceConductList();
        }

        private void BindProduceConductList() {
            this.CreateNewThread(() => {
                this._produceConductList = this._produceConductProcessor.FetchProduceConductViewModelList(this._searchModel, this._pageIndex);
            }, () => {
                this.dgvProduceConductList.DataSource = new SortableBindingList<ProduceConductViewModel>(this._produceConductList);
                this.pceList.Records = this._searchModel.Records;
                this.pceList.DataBind();
            });
        }

        private void ShowEditForm(string title, List<ProduceConduct> produceConductList) {
            this.CreateNewThread(() => {
                Thread.Sleep(100);
            }, () => {
                ProduceConductEditControl editControl = new ProduceConductEditControl();
                this.FormEdit = new FrmEdit();
                editControl.BaseEditModel = produceConductList;
                editControl.ValidatorForEdit = this.FormEdit.validatorForEdit;
                this.FormEdit.Controls.Add(editControl);
                this.FormEdit.Edit += new FrmEdit.EditEventHandler(frmEdit_Edit);
                this.FormEdit.Text = string.Format("{0}{1}", title, this.Text);
                FrmEntry.LoadAndRunDialog(this.FormEdit);
            });
        }

        #endregion

        private void FrmProduceConduct_Load(object sender, EventArgs e) {
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                this._produceConductProcessor = new ProduceConductProcessor(this.pceList.PageSize);
                this._searchModel = new ProduceConductSearchModel();
                this._pageIndex = 1;
            }, () => {
                this.WindowState = FormWindowState.Maximized;
                this.ResetForms();
                this.PreventCancel = false;
            });
        }

        private void pceList_Paging(object sender, PaginationArgs e) {
            this._pageIndex = e.PageIndex;
            this.BindProduceConductList();
        }

        private void dgvProduceConductList_DoubleClick(object sender, EventArgs e) {
            if (this.dgvProduceConductList.CurrentRow != null) {
                int customerId = (int)this.dgvProduceConductList.CurrentRow.Cells["Key"].Value;
            }
        }

    }
}
